from pickle import TRUE
from sanic.response import json
from sanic import Blueprint
from playhouse.shortcuts import model_to_dict,dict_to_model
from model.model import TOrder
import time,uuid

rt = Blueprint("order",url_prefix="order")

# list
@rt.get("/")
def indexHandle(req):
    rows = TOrder.select()
    res = []
    for m in rows:
        res.append(model_to_dict(m))
    return json({
            "msg":"ok",
            "code":0,
            "data":res
    })

# add
@rt.post("/")
def indexHandle(req):
    msg=""
    try:
        m = dict_to_model(TOrder,req.json)
        m.cid=uuid.uuid1()
        m.createat=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        m.updateat=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        m.save(force_insert=TRUE)
        msg="ok"
    except Exception as e:
        msg = e
    return json({
            "msg":msg,
            "code":0,
            "data":{}
    })

# detail
@rt.get("/<id>")
def indexHandle(req,id):
    m = TOrder.get_or_none(TOrder.oid==id)
    res = m if (m is None) else model_to_dict(m)
    return json({
            "msg":"ok",
            "code":0,
            "data":res
    })

# update
@rt.post("/<id>")
def indexHandle(req,id):
    m = TOrder.get_or_none(TOrder.oid==id)
    res = m if (m is None) else model_to_dict(m)
    return json({
            "msg":"this is book",
            "code":0,
            "data":res
    })